﻿// --------------------------------------------------------------------------------------------------------------------
// <copyright file="wNewTicket.xaml.cs" company="Mar3ek">
//   http://mar3ek.wordpress.com
// </copyright>
// <summary>
//   Interaction logic for wNewTicket.xaml
// </summary>
// --------------------------------------------------------------------------------------------------------------------

// ReSharper disable InconsistentNaming

using System.Collections;
using System.Collections.Generic;
using System.Collections.ObjectModel;
using System.Windows;
using LighthouseNET;

namespace Mar3ek.HouseLight
{
    /// <summary>
    /// Interaction logic for wNewTicket.xaml
    /// </summary>
    public partial class wNewTicket
    {
        private readonly int _projectId;
        private readonly LighthouseAPI _api;
        private readonly bool _editing;
        private readonly Ticket _ticket;

        /// <summary>
        /// Initializes a new instance of the <see cref="wNewTicket"/> class.
        /// </summary>
        /// <param name="api">
        /// The api instance.
        /// </param>
        /// <param name="project">
        /// The project.
        /// </param>
        /// <param name="milestones">
        /// The milestones.
        /// </param>
        public wNewTicket(LighthouseAPI api, Project project, ICollection milestones, IList<User> users)
        {
            InitializeComponent();
            _projectId = project.Id;
            _api = api;
            cbMilestone.DataContext = milestones;
            cbUsers.DataContext = users;

            if (milestones.Count > 0)
            {
                cbMilestone.SelectedIndex = 0;
            }
            else
            {
                chkMilestone.IsEnabled = false;
            }

            if (users.Count > 0)
            {
                cbUsers.SelectedIndex = 0;
            }
            else
            {
                chkUsers.IsEnabled = false;
            }

            cbState.DataContext = project.TicketStates;
            if (project.TicketStates.Count > 0)
            {
                cbState.SelectedIndex = 0;
            }

            Result = false;
        }

        /// <summary>
        /// Initializes a new instance of the <see cref="wNewTicket"/> class.
        /// </summary>
        /// <param name="api">
        /// The API instance
        /// </param>
        /// <param name="ticket">
        /// The ticket.
        /// </param>
        /// <param name="project">
        /// The project.
        /// </param>
        /// <param name="milestones">
        /// Project milestones
        /// </param>
        public wNewTicket(LighthouseAPI api, Ticket ticket, Project project, Collection<Milestone> milestones, IList<User> users)
        {
            InitializeComponent();
            _api = api;
            Title = "Editing ticket";
            _ticket = ticket;
            _editing = true;
            txtTicketTitle.Text = ticket.Title;
            cbMilestone.DataContext = milestones;
            txtTags.Text = ticket.Tag;
            txtBody.Text = ticket.RawBody;
            cbState.DataContext = project.TicketStates;
            Result = false;
            cbUsers.DataContext = users;

            if (ticket.MilestoneId > 0)
            {
                cbMilestone.SelectedValue = ticket.MilestoneId;
                chkMilestone.IsChecked = true;
            }

            if (users.Count > 0)
            {
                cbUsers.SelectedIndex = 0;
            }
            else
            {
                chkUsers.IsEnabled = false;
            }

            if (ticket.AssignedUserId > 0)
            {
                cbUsers.SelectedValue = ticket.AssignedUserId;
                chkUsers.IsChecked = true;
            }

            cbState.SelectedValue = ticket.State;
        }

        /// <summary>
        /// Gets a value indicating whether an update has been sent.
        /// </summary>
        /// <value>
        ///   <c>true</c> if sent; otherwise, <c>false</c>.
        /// </value>
        internal bool Result { get; private set; }

        /// <summary>
        /// Handles the Loaded event of the Window control.
        /// </summary>
        /// <param name="sender">The source of the event.</param>
        /// <param name="e">The <see cref="System.Windows.RoutedEventArgs"/> instance containing the event data.</param>
        private void Window_Loaded(object sender, RoutedEventArgs e)
        {
            if (_ticket.MilestoneId > 0)
            {
                cbMilestone.SelectedValue = _ticket.MilestoneId;
            }
        }

        /// <summary>
        /// Handles the Click event of the btnSubmit control.
        /// </summary>
        /// <param name="sender">The source of the event.</param>
        /// <param name="e">The <see cref="System.Windows.RoutedEventArgs"/> instance containing the event data.</param>
        private void btnSubmit_Click(object sender, RoutedEventArgs e)
        {
            if (string.IsNullOrEmpty(txtTicketTitle.Text) || string.IsNullOrEmpty(txtBody.Text))
            {
                return;
            }

            if (chkMilestone.IsChecked == true && cbMilestone.SelectedIndex == -1)
            {
                return;
            }

            var milestoneId = chkMilestone.IsChecked == true && cbMilestone.SelectedValue != null ? (int)cbMilestone.SelectedValue : 0;
            var userId = chkUsers.IsChecked == true && cbUsers.SelectedValue != null ? (int)cbUsers.SelectedValue : 0;
            try
            {
                if (_editing)
                {
                    _api.UpdateTicket(_ticket.ProjectId, _ticket.Number, new Ticket(txtTicketTitle.Text, txtBody.Text, cbState.SelectedValue.ToString(), userId, milestoneId, txtTags.Text));
                }
                else
                {
                    _api.CreateTicket(_projectId, new Ticket(txtTicketTitle.Text, txtBody.Text, cbState.SelectedValue.ToString(), userId, milestoneId, txtTags.Text));
                }

                Result = true;
                Close();
            }
            catch (LighthouseResponseException ex)
            {
                MessageBox.Show(
                    ex.Message,
                    "HouseLight", 
                    MessageBoxButton.OK,
                    MessageBoxImage.Error);
            }
            catch (LighthouseServerException ex)
            {
                MessageBox.Show(
                    string.Format("A communication error was encountered. Check your internet connection and try again.\nIf the problem persists, contact the plugin developer.\nError details follow:\n\n{0}", ex.Message),
                    "HouseLight",
                    MessageBoxButton.OK,
                    MessageBoxImage.Error);
            }
        }

        /// <summary>
        /// Handles the Click event of the btnCancel control.
        /// </summary>
        /// <param name="sender">The source of the event.</param>
        /// <param name="e">The <see cref="System.Windows.RoutedEventArgs"/> instance containing the event data.</param>
        private void btnCancel_Click(object sender, RoutedEventArgs e)
        {
            Close();
        }
    }
}

// ReSharper restore InconsistentNaming